package com.yksj.healthtalk.ui.salon;

import java.util.ArrayList;
import java.util.TreeMap;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.SalonInComeAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.SalonInComeEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.WheelUtils;

public class SalonInComeActivity extends BaseFragmentActivity implements OnClickListener,OnItemClickListener,OnRefreshListener<ListView>{
	
	private PullToRefreshListView mPullToRefreshListView;
	private ListView mListView;
	private TextView mTitleName;
	private Button mTitleButton;
	private Button mTitleBackBtn;
	private TextView startingTimeTextView;
	private TextView endingTimeTextView;
	private ArrayList<SalonInComeEntity> entities;//数据的实体类
	private TreeMap<SalonInComeEntity, ArrayList<SalonInComeEntity>> treeMap;
	private ArrayList<SalonInComeEntity> classifyEntities;
	private SalonInComeAdapter mSalonInComeAdapter;
	private PopupWindow mPopBottom;
	private Button agewheelCancel;
	private Button agewheelSure;
	private PopupWindow agepop;
	private TextView isClickedTextView;
	private View mainView;
	private String type = "0";//类型
	private String  PAGE_FLAG = "0";//表示翻页标记
	private TextView totalMoney;
	private String groupId ;
	public static String inComeMoney ="0" ;
	public  ArrayList<SalonInComeEntity> cacheSalonInComeEntity;//缓存 下拉刷新更多
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.salon_income);
		initWidget();
		initData();
	}
	
	private void initWidget() {
		// TODO Auto-generated method stub
		mainView = LayoutInflater.from(this).inflate(R.layout.salon_income, null);
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.hall);
		mListView = mPullToRefreshListView.getRefreshableView();
		mTitleName = (TextView) findViewById(R.id.title_lable);
		mTitleButton = (Button) findViewById(R.id.title_right);
		startingTimeTextView = (TextView) findViewById(R.id.starting_time);
		endingTimeTextView = (TextView) findViewById(R.id.ending_time);
		mTitleBackBtn = (Button)findViewById(R.id.title_back);
		totalMoney = (TextView) findViewById(R.id.total_tv);
		
		startingTimeTextView.setOnClickListener(this);
		endingTimeTextView.setOnClickListener(this);
		mTitleButton.setOnClickListener(this);
		mListView.setOnItemClickListener(this);
		mTitleBackBtn.setOnClickListener(this);
		mPullToRefreshListView.setOnRefreshListener(this);
	}

	private void initData() {
		//接受传过来的数据
		if (getIntent().hasExtra("entities")) {
			entities = (ArrayList<SalonInComeEntity>) getIntent().getExtras().get("entities");
		}else {
			entities = new ArrayList<SalonInComeEntity>();
		}
		
		if (getIntent().hasExtra("groupId")) {
			groupId =	getIntent().getExtras().getString("groupId");
		}
		
		mTitleName.setText("收入统计");
		mTitleButton.setBackgroundResource(R.drawable.icon_more);
		totalMoney.setText(String.format(getResources().getString(R.string.money), 0));
		
		treeMap = statisticalInformation(entities);
		mSalonInComeAdapter = new SalonInComeAdapter(getApplicationContext(), treeMap,this);
		mListView.setAdapter(mSalonInComeAdapter);
	}

	@Override
	public void onClick(View v) {
//		0 全部  1 门票 2图片 3文件 4语音
		switch (v.getId()) {
		case R.id.title_right:
			showMenu(v);
			break;
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.all:
			type ="0";
			entities.clear();
			isGetSalonIncome();
			showMenu(v);
			break;
		case R.id.ticket:
			type ="1";
			entities.clear();
			isGetSalonIncome();
			showMenu(v);
			break;
		case R.id.voice:
			type ="4";
			entities.clear();
			isGetSalonIncome();
			showMenu(v);
			break;
		case R.id.file:
			type ="3";
			entities.clear();
			isGetSalonIncome();
			showMenu(v);	
			break;
		case R.id.starting_time:
			isClickedTextView = startingTimeTextView;
			setDate();
			break;
		case R.id.ending_time:
			isClickedTextView = endingTimeTextView;
			setDate();
			break;
		case R.id.wheel_cancel_age:
			if (agepop != null)
				agepop.dismiss();
			break;

		case R.id.wheel_sure_age:
			if (agepop != null)
				agepop.dismiss();
			if (WheelUtils.getCurrent() != null) {
				String age = WheelUtils.getCurrent();
				isClickedTextView.setText(age);
			}
			isGetSalonIncome();
			break;
		default:
			break;
		}
		if (v instanceof LinearLayout) {
			String date = (String) v.getTag();
			Intent intent = new Intent(getApplicationContext(),SalonIncomeDetailActivity.class);
			intent.putExtra("date", date);
			startActivity(intent);
		}
	}
	
	/**
	 * 判断是否访问请求
	 */
	private Boolean isGetSalonIncome() {
		// TODO Auto-generated method stub
		String startTime;
		String endTime;
		if (!(startTime = startingTimeTextView.getText().toString().trim()).equals("")&&!(endTime = endingTimeTextView.getText().toString().trim()).equals("")) {
			startTime = startTime.replaceAll("\\D", "")+"000000";
			endTime = endTime.replaceAll("\\D", "")+"000000";
			entities.clear();
			getIncome(startTime, endTime, type, PAGE_FLAG);
			return true;
		}else {
			ToastUtil.showShort(getApplicationContext(), "请选择日期");
			return false;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		onClick(view.findViewById(R.id.list_lin));
	}
	
	/**
	 * 时间的统一整理
	 */
	public TreeMap<SalonInComeEntity, ArrayList<SalonInComeEntity>> statisticalInformation(ArrayList<SalonInComeEntity> entities){
		TreeMap<SalonInComeEntity, ArrayList<SalonInComeEntity>> map = new TreeMap<SalonInComeEntity, ArrayList<SalonInComeEntity>>();
		for (int i = 0; i < entities.size(); i++) {
			map.put(entities.get(i), entities.get(i).getEntities());
		}
		return map;
	}
	
	/**
	 * pop的显示
	 * @param view
	 */
	private void showMenu(View view){
		if(mPopBottom == null){
			LayoutInflater inflater = LayoutInflater.from(this);
			View v = inflater.inflate(R.layout.salon_income_pop_top,null);
			mPopBottom = new PopupWindow(v,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,true);
			mPopBottom.setBackgroundDrawable(new BitmapDrawable());
			mPopBottom.setFocusable(true);
			RadioGroup radioGroup  = (RadioGroup)v.findViewById(R.id.radiogroup);
			int count = radioGroup.getChildCount();
			for (int i = 0; i < count; i++) {
				radioGroup.getChildAt(i).setOnClickListener(this);
			}
		}else if(mPopBottom.isShowing()){
			mPopBottom.dismiss();
			return;
		}
		mPopBottom.showAsDropDown(view);
	}

	
	/**
	 * 设置日期
	 */
	private void setDate() {
		LayoutInflater inflater = LayoutInflater.from(this);
		View agewheelView = inflater.inflate(R.layout.agewheel, null);
		agewheelCancel = (Button) agewheelView
				.findViewById(R.id.wheel_cancel_age);
		agewheelSure = (Button) agewheelView.findViewById(R.id.wheel_sure_age);
		agewheelCancel.setOnClickListener(this);
		agewheelSure.setOnClickListener(this);
		agepop = new PopupWindow(agewheelView, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
//		String[] str1 = getResources().getStringArray(R.array.year);
//		String[] str2 = getResources().getStringArray(R.array.month);
//		String[] mon1 = getResources().getStringArray(R.array.mon1);
//		String[] mon2 = getResources().getStringArray(R.array.mon2);
//		String[] mon3 = getResources().getStringArray(R.array.mon3);
//		String[] mon4 = getResources().getStringArray(R.array.mon4);
//		WheelUtils.setThirdWheel(this, str1, str2, mon1, mon2, mon3, mon4,
//				mainView, agepop, agewheelView);
	}
	
	/**
	 * 请求数据统计的数据
	 * @param startTime
	 * @param endTime
	 * @param Type
	 * @param pageSzie
	 * @param pageNum
	 */
	public void getIncome(String startTime,String endTime,String Type,String pageFlag){
		if (groupId == null || groupId.equals("")) {
			ToastUtil.showShort(this, "groupId is null");
			return;
		}
		HttpRestClient.doHttpFindIncome(groupId , SmartFoxClient.getSmartFoxClient().getUserId(), startTime, endTime, type, pageFlag, new AsyncHttpResponseHandler(){
			
			@Override
			public void onSuccess(int statusCode, String content) {
//				if (cacheSalonInComeEntity == null) {
					  cacheSalonInComeEntity = new ArrayList<SalonInComeEntity>();
//				}/
			    JsonParseUtils.getSalonInCome(content,cacheSalonInComeEntity);
			    entities.addAll(cacheSalonInComeEntity);
			    treeMap.clear();
				treeMap.putAll(statisticalInformation(entities));
				//总金额
				totalMoney.setText(String.format(getResources().getString(R.string.money),Integer.valueOf(inComeMoney)));
				mSalonInComeAdapter.setIterator(treeMap.keySet().iterator());
				mSalonInComeAdapter.notifyDataSetChanged();
				super.onSuccess(statusCode, content);
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				 treeMap.clear();
				 totalMoney.setText(String.format(getResources().getString(R.string.money),0));
				 mSalonInComeAdapter.setIterator(treeMap.keySet().iterator());
				 mSalonInComeAdapter.notifyDataSetChanged();
				 ToastUtil.showShort(getApplicationContext(), "请求失败,请重新请求");
				// TODO Auto-generated method stub
				super.onFailure(error, content);
			}
			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				super.onFinish();
			}
		});
	}
	
	@Override
	public void onBackPressed() {
		LodingFragmentDialog.dismiss(getSupportFragmentManager());
		finish();
		super.onBackPressed();
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		
	}
	
	
//	/**
//	 * 总共的收入
//	 * @param entities
//	 */
//	public int showTotalMoney(ArrayList<SalonInComeEntity> entities){
//		for (int i = 0; i < entities.size(); i++) {
//			money = money + Integer.valueOf(entities.get(i).getChangeNum());
//		}
//		return money;
//	}
}
